Author - StudySection Post Views - 22 views
required field

Handling the whitespace issues for textarea, which is a required field

For any input types that are required fields, we generally face whitespace issues. In Whitespace issues, required fields allow users to type space or tab, which means non-printable characters. Generally, we want to prohibit web forms to submit blank and non-printable characters for required fields.

To avoid submission of non-printable characters on a form for required fields, we use a pattern attribute along with the required attribute for inputs, as shown below:
<input type="text" class="form-control" placeholder="First Name" name="fname" id="fname" maxlength="64" pattern=".*\S+.*" required/>

The above pattern attribute validates the field to type only printable characters.
For inputs, the pattern attribute works perfectly. I tried the same approach for textarea as well, as shown below.
<textarea class="form-control" placeholder="Note" name="note" id="note" maxlength="100" pattern=".*\S+.*" required/>

But, textarea continues to allow non-printable characters to submit irrespective of the required field, as textarea doesn’t support the pattern attribute.
Now, what is the solution to handle the whitespace-characters-issue for textarea? With the help of a javascript/jquery script, we can resolve our issue. Let’s see:
function checkTextareaValidity(textareaObj) {
var re = /^.*\S+.*$/;
if((re).test(textareaObj.val())) {
textareaObj[0].setCustomValidity("");
return true;
}
else {
textareaObj[0].setCustomValidity("invalid");
return false;
}
}
$(document).on('submit', '#add_info_form', function(e) {
var form = $("#add_info_form'");
var textareaObj = $('#add_info_form' textarea[required]');
if (form[0].checkValidity() === false) {
e.preventDefault();
e.stopPropagation();
alert("Please fill required fields");
} else {
e.preventDefault();
if(checkTextareaValidity(textareaObj) === false) {
return false;
}
//further code if textarea is successfully validated
});

First, you will see the checkTextareaValidity function to check whether a textarea has at least one printable character or not.

In the form to submit an event, first, all html5 validation will be performed. If the form submit passes the validation, then we will perform textarea validation and accordingly proceed further.

If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level PHP Certification Exams are offered by StudySection along with other programming certification exams.

Leave a Reply

Your email address will not be published.