0

I have a problem with input validation using pattern and required attribute. The idea is that I want to use my own title, not the browser's. When I want to complete the input with characters that not correspond with the regex (numbers), message 'Only letters allowed' displays near the input. But when I complete with letters it shows me the same message that my characters are incorrect. Who knows what is the problem? Thank you.

<script type="text/javascript">
function validation (textbox) {
    var regex = /^[a-zA-Z]+$/;

    if (textbox.value == '') {
        textbox.setCustomValidity('Required field');
    }
    else if(!regex.test(textbox.value)){
        textbox.setCustomValidity('Only letters allowed');
    }
    else {
        textbox.setCustomValidity('');
    }

    return true;
}

FORM input:

<input type="text" id="first-name" name="first_name" placeholder="First Name" oninvalid="validation(this);" required="requied" pattern="/^[a-zA-Z]+$/"/>
aniski
  • 1,263
  • 1
  • 16
  • 31
  • Try to use ... pattern="^[a-zA-Z]+$" /> instead of ... pattern="/^[a-zA-Z]+$/" /> – Dek4nice May 15 '16 at 14:23
  • 1
    Do you want to display custom text in validation message? – Mohammad May 15 '16 at 14:51
  • If you're looking for custom text validation and having issues with default browser validation, this might help: http://stackoverflow.com/questions/10361460/how-can-i-change-or-remove-html5-form-validation-default-error-messages – Stu Furlong May 15 '16 at 16:08

0 Answers0