Home > Mobile >  Name and Surname validation using regular expressions (JavaScript)
Name and Surname validation using regular expressions (JavaScript)

Time:06-17

Using regular expressions check that the name and surname contain only uppercase and lowercase letters of Latin and Cyrillic, spaces and dashes (minus sign).

The first character must be a capital letter of Latin or Cyrillic, the other characters must be lowercase letters of Cyrillic or Latin; after the second character, a space or dash is allowed; after a space / dash the word must start with a capital letter again, and the other letters must be lowercase; again after the second character there may be a new space / dash, but at the end it must end with a word beginning with a capital letter; it is not allowed to stand two spaces or dashes next to each other, nor a space and a dash, it must contain at least one space / dash. It must not be shorter than 5 characters or longer than 180.

In case the name and surname are not in the correct format, show an orange box around the field and below the field, in orange letters show the error "Name and surname not written correctly". Show the error after leaving the field for entering the name and surname.

If the user corrects the name and surname, after leaving the field again, remove the orange box and the error below.

Names available:

Петар Петровић
Petar Petrović
Petar Petrovic
Petar Petrović-Njegoš
Jovana-Stefanija Ivanović-Vasić Petrović

Invalid names and surnames:

Ud A
Уд Aд
Уд_Ад
Ud. Ad
Петар 2 Петровић
Petar P Petrović
Jovan J. Jovanović
P2etar Grbić
Petar Petrović-njegoš
Petar petrović

$(function() {
  $('#imeprezime1').on('blur', function(e) {
    var provera = /^([A-Z]{1})([a-z]{1,80})([\-|\s]{0,1}[A-Z]{1}[a-z]{1,50})*$/.test($(this).val());
    if (provera === true) {
      $(this).css('outline', '0px solid');
    } else {
      $(this).css('outline', '4px solid orange');
      $(this).after('<span style="color: orange;">Име и презиме није правилно написано</span><br>')
    }
  });

  $('#imeprezime1').on('focus', function(e) {
    $(this).next("span").remove();
    $(this).next("br").remove();
  });
});

How can I limit the number of characters and add Cyrillic? Also Fname and Lname is required. Thanks!

CodePudding user response:

As the strings contain Serbo-Croatian characters too, I check them as well.

(?=^.{5,180}$)^[А-Я][а-яčćžđšžћ] (?:[\s-][А-Я][а-яčćžđšžћ] ) $|^[A-Z][a-zčćžđšžћ] (?:[\s-][A-Z][a-zčćžđšžћ] ) $

Regex Explanation

  • (?=^.{5,180}$) Asserts that the string length be at least 5 and at most 180
  • ^[А-Я][а-яčćžđšžћ] (?:[\s-][А-Я][а-яčćžđšžћ] ) $ Matches names in latin (and Serbo-Croatian) letters
  • ^[A-Z][a-zčćžđšžћ] (?:[\s-][A-Z][a-zčćžđšžћ] ) $ Matches names in Cyrillic (including Serbo-Croatian) letters

Also, see the regex demo

var provera = /(?=^.{5,180}$)^[А-Я][а-яčćžđšžћ] (?:[\s-][А-Я][а-яčćžđšžћ] ) $|^[A-Z][a-zčćžđšžћ] (?:[\s-][A-Z][a-zčćžđšžћ] ) $/.test($(this).val());
  • Related