简体   繁体   English

为什么正则表达式只验证字段中的一个字符而不输入全部字符

[英]why regex is only validating one character from the field and not all entered

In javascript i am attempting to validate a first name in a form using 在JavaScript中,我尝试使用以下方式验证表单中的名字

var regex = /([a-zA-Z'-])+/; var regex = /([[a-zA-Z'-])+ / ;;

however if there is a character is accepts such as a letter and a character it shouldnt accept such as a number it still validates it. 但是,如果有一个字符被接受(例如字母)和一个字符不被接受(例如数字),它仍然会对其进行验证。 It only doesn't validate it if it is all numbers. 如果全部为数字,则不进行验证。 Only letters, hypens and apostrophes are allowed in firstName. firstName中仅允许使用字母,连字符和撇号。 Am i supposed to add something to the regex code to make it validate everything in the text box? 我是否应该在正则表达式代码中添加一些内容以使其验证文本框中的所有内容?

I suggest you to add anchors. 我建议您添加锚点。 Anchored regex will do an exact string match. 锚定的正则表达式将进行精确的字符串匹配。

var regex = /^[a-zA-Z'-]+$/;

^ asserts that we are at the start and $ asserts that we are at the end. ^断言我们在开始,而$断言我们在结束。

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

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