简体   繁体   中英

JavaScript regex to validate an input is more than 0 characters

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 (ie 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

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).

使用/.+/.表示所有可能的字符(换行符除外, +表示至少一次)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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