简体   繁体   English

使用正则表达式验证文本输入字段的内联样式?

[英]Validate a text input field for inline styles using regex?

I have a simple text field which I need to validate with a regex. 我有一个简单的文本字段,需要使用正则表达式进行验证。
The text field is supposed to contain inline-styles in the "proper" format xxx: xxx; 文本字段应包含“正确”格式xxx:xxx;的内联样式。

Ex: font-size: 15px; 例如:font-size:15像素; background: #33333; 背景:#33333; -webkit-transition: background-color 500ms ease-out 1s; -webkit-transition:背景色500ms缓和1s;

Any regex gurus out there help me out here. 那里的任何正则表达式专家都可以帮助我。 I'll eventually find the solution on my own but that may take awhile. 我最终将自己找到解决方案,但这可能需要一段时间。

Languages would be javascript for client side validation then moving onto php for the server side validation. 语言将是用于客户端验证的javascript,然后转移到用于服务器端验证的php。

Thanks a bunch guys... I came up with this -- /([az-]+: [0-9a-z#(). -]+;$)/g --. 谢谢一群人...我想到了-/([az-] +:[0-9a-z#()。-] +; $)/ g-。 I would answer myself but I'm unsure if its the best solution. 我会回答自己,但不确定是否是最佳解决方案。

Gonna accept the most detailed answer below from @nu11p01n73R as I stole the $ sign from his explanation that made the above work right. 我将从@ nu11p01n73R接受以下最详细的答案,因为我从他的使上述工作正确的解释中窃取了$符号。

Now is there an issue with what I came up with? 现在我的想法有问题吗? Know I'm not technically supposed to ask but I think its easier to read for me to read, anyways. 知道我在技术上不应该问这个问题,但是无论如何,我认为它更易于阅读。 I love SO. 我很喜欢

You can use a regex of the form 您可以使用以下形式的正则表达式

^([^:]+:[^;]+;)+$

see for example http://regex101.com/r/cE6yS6/3 参见例如http://regex101.com/r/cE6yS6/3

  • ^ anchors the regex at the begining of the string. ^将正则表达式锚定在字符串的开头。 ensures that nothing presceds the matched string 确保没有任何东西先于匹配的字符串

  • [^:]+: matches anything other than : followed by a : [^:]+:匹配除:之后的:

  • [^;]+; matches anything other than ; 匹配以外的任何东西; followed by ; 其次;

  • + quantifier, repeats the occurence of property:value; +量词,重复出现property:value;

  • $ anchors the regex at the end of the string. $将正则表达式锚定在字符串的末尾。 Ensures nothing follows the matches string. 确保在matchs字符串后没有任何内容。

try this better solution : 试试这个更好的解决方案:

^([a-zA-Z\-\s]+:[a-zA-Z0-9\-\s#%\(\)\+']*;)+$

it handles exception case: 它处理异常情况:

ex1=font-size: 15px; background: #33:333; //not match
ex2=font-size: 15px; background: #33333;  //match

for html: 对于html:

<input type="text"  pattern="^([a-zA-Z\-\s]+:[a-zA-Z0-9\-\s#%\(\)\+']*;)+$" style="width: 1000px;"/>

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

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