JavaScript regex to validate an input is more than 0 characters

爷,独闯天下 提交于 2021-02-11 18:05:13

问题


Forgive me if this is super simple, but I googled and googled and couldn't find a good example. I'm not that great with regex and just need to valid that an input has more than 1 character (i.e. is not blank). I'm using Angular ng-pattern.

<input type="text" ng-model="username" ng-pattern="/regex/">

I need to verify that there as something in the input (not empty). I've used a couple of example, but the issue is once you clear the input, angular is still seeing the pattern as valid. I need it to fail once the input is empty again, but not on first load. As always all help is much appreciated.

EDIT: I basically need a regex that will verify the field is not blank. Here is a plnkr


回答1:


You can just use required for that:

<input type="text" ng-model="username" name="username" required>

See this pluckr fork: http://plnkr.co/edit/VwY1WPdCocKHwww69ZSj?p=preview

More in the docs: http://docs.angularjs.org/api/ng.directive:input#usage_parameters

If you REALLY want to use ng-pattern you should add start/end of input (^ and $):

<input type="text" ng-model="username" ng-pattern="/^$/">

But remember, this will validate a blank input (the input value matches the pattern).




回答2:


Use /.+/ (. means every possible character (except from new line characters and + means at least once)



来源:https://stackoverflow.com/questions/20503193/javascript-regex-to-validate-an-input-is-more-than-0-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!