code-daily
code-daily

Reputation: 23

How to do validation of the form fields in for various inputs?

I got a filed in a form for text area and all other are input elements.

I am not able to use the same for text area as its not supported for the above method that is being used.

I want to get a function , if the input is invalid then return false which adds the class invalid and show the errror message.

Can anyone guide , what the alternative method I can use here instead of checkValidity to perform the validation on text area?

I tried using the below function but the event is not getting picked up

function validateTxt(textArea) {
  const reg = new RegExp("^[a-zA-Z0-9]+$")
  if (!reg.test(textArea.value)) {
    return false
  }
  return true
}

Upvotes: 2

Views: 100

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

The pattern attribute is not supported on the textarea element. You need to implement it yourself. This can be done by setting its value in a data attribute, which you use to create a RegExp in the input event handler to validate the value against. You can then toggle the class on the element as required.

Try this:

$('textarea').on('input', e => {
  const $textarea = $(e.target);
  const valid = new RegExp($textarea.data('pattern')).test($textarea.val());
  $textarea.toggleClass('invalid', !valid);  
});
.invalid {
  border: 2px solid #C00;
  color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<textarea type="text" class="form txt" id="message" data-pattern="^[a-zA-Z0-9]+$"></textarea>

Upvotes: 1

Related Questions