简体   繁体   English

验证输入字段 Fullname(Firstname,Lastname) - JavaScript

[英]Validation input field Fullname(Firstname,Lastname) - JavaScript

Need validation for full name(first name/last name - 1 input field).需要验证全名(名字/姓氏 - 1 个输入字段)。 I'm new in this sphere and can't formulate the right syntax maybe will work with a regular expression too我是这个领域的新手,无法制定正确的语法,也许也适用于正则表达式

<form name="myForm" action="#" id="form" onsubmit="return validateForm()" method="POST">
            <div class="field"><span class="input"><i class="fas fa-user-alt"></i>
                    <input type="text" id="name" name="Fullname" placeholder="Full Name" >
                </span>


function validateForm() {
var name= document.getElementById('name').value;
var x = name.indexOf(" ");
var fname = name.substring(0, x);
var lname = name.substring(x).trim();
if ( 17 < fname.value.length < 5 || 4 > lname.value.length > 17 || x.value.length != 1) {
    alert("try again")
    return false;
 }
 alert("OK")
return true;
}

The field (1 field) should contain 2 words which should be from 3 to 20 symbols.字段(1 个字段)应包含 2 个字,应为 3 到 20 个符号。

EDIT:It seems work..finally!编辑:它似乎工作..终于!

 function input (name) { let fullNameArr = name.split('') const space = ' ' let firstName = '' if (fullNameArr.includes(space)) { for (let i = 0; i < fullNameArr.length; i++) { if (!firstName.includes(space)) { firstName += fullNameArr[i] } } } firstName = fullNameArr.splice(0, firstName.length) const lastName = fullNameArr if (firstName.length > 3 && firstName.length <= 21 && lastName.length >= 3 && lastName.length <= 20 && lastName.includes(space) === false) { console.log(firstName) console.log(lastName) } else { console.log('Invalid Name') return false } } input('Todor Markov')

Your model makes several assumptions about names.您的模型对名称做了几个假设。 Having first name and last name as separate input boxes is typically done to remove this barrier.通常将名字和姓氏作为单独的输入框来消除这个障碍。

From a UX standpoint, if you were not going to have separate fields, you'd need some validation with a tooltip that checked if the user has more than one space that alerts them they must type FirstName LastName .从 UX 的角度来看,如果您不打算有单独的字段,则需要使用工具提示进行一些验证,以检查用户是否有多个空格提醒他们必须键入FirstName LastName

From a regex validation view, here's a catch all to ensure it's valid.从正则表达式验证的角度来看,这里有一个确保它有效的方法。
/^[az ,.'-]+$/i.test("Johnny 'Van' Pat-ton Jr.") No numbers, but allow letters and the special characters ,.'- . /^[az ,.'-]+$/i.test("Johnny 'Van' Pat-ton Jr.")没有数字,但允许使用字母和特殊字符,.'-

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM