HTML - Using pattern attribute - regex

In html form, I need textarea which allows any type of text: numbers, symbols, newline or letters, including Hebrew letters. The only two rules:
The input must include the string: "{ser}"
The input should prohibit any use of "{" or "}" except for the above string
I tried this:
<form action="#">
...
<textarea pattern="[^\{\}]*\{ser\}[^\{\}]*" required>
האם אתה נמצא בשבת הקרובה? אם כן נא השב {ser} + שם מלא
</textarea>
...
<input type="submit" />
...
</form>
But for some reason it also allows sending texts that do not meet the rules. I would appreciate your help.

You cannot use pattern attribute on textareas, see the documentation.
maxlength specifies a maximum number of characters that the
is allowed to contain. You can also set a minimum length that is
considered valid using the minlength attribute, and specify that the
will not submit (and is invalid) if it is empty, using the
required attribute. This provides the with simple
validation, which is more basic than the other form elements (for
example, you can't provide specific regexs to validate the value
against using the pattern attribute, like you can with the input
element).
Perhaps implement a regex match with javascript?
function validateTextarea(text) {
var re = /ser/g;
var result = text.match(re);
if(result != null && result.length > 0)
// Do something
}
Then probably the best way is to check the function in onsubmit form attribute.

Related

Regex Text Input Validation

I'm way in over my head here, but trying to learn.
Attempting to use text input validation on Cognito forms by way of a custom regular expression.
I'm trying to capture users work email in an online form. In the "work email" field they would only be able to enter the text to the left of the # and then once they type "#" it'll automatically populates the "organization.com." I'll probably want to make sure that the user cant enter spaces, and other characters (ie:'*&^%$#!)
Been googling how to do this but no luck so far. I'm sure I'm using the wrong terminology to describe what i'm trying to accomplish.
This does everything you need except handle the actual submission of the data.
document.querySelector('input').oninput = function () {
if (this.value.endsWith('#')) {
this.value += 'organization.com';
}
}
<form>
<input type=email pattern=.*#organization\.com$ title='name#organization.com' required />
<button type=submit>Submit</button>
</form>

Angular2 - Why does my reactive form input with an html pattern attribute is not validating correctly?

I'm struggling with a problem that I can't understand:
I need to validate an input field with a pattern="[0-9]+([,.][0-9])?" attribute on an angular reactive form with Validators.pattern, but it seems my ? quantifier at the end is not working...
What I want
I want to validate numbers with zero or one decimal maximum. As you can see on https://regex101.com/r/2D2sww/1, the regex is working great.
The actual problem
In my app I can enter as many decimals as I want without the Validator.pattern to do anything. Any other character invalidate the form, so my Validator is working.
Here is my code (simplified):
component.html
<form [formGroup]="myForm">
<input type="number" formControlName="myInputField" id="myInputField" pattern="[0-9]+([,.][0-9])?" required />
</form>
component.ts (Every import and declarations are skipped for clarity)
ngOnInit() {
this.myForm = this.formBuilder.group({
myInputField: [
"",
[Validators.required, Validators.pattern],
]
});
}
I already tried to use Validators.pattern(/^[0-9]+([,.][0-9])?$/) and Validators.pattern("[0-9]+([,.][0-9])?") as pointed in the documentation, but it doesn't change anything, so I suspect my Regex to be incorrect...
Any ideas ? Thanks, have a nice day :)
I think there is nothing wrong with your validator pattern regex,
you can remove the pattern's attribute from the input, it is redundant because you are initiating it from inside the ts file: 'myInputField': new FormControl(null, [Validators.pattern('^[0-9]+([,.][0-9])?$')]).
StackBlitz

Match inputs of two text fields

Scenario: I have two input fields. One of them will accept an input in form which the user will decide. The other field should match the format defined in first field. For example, if the user enters format like anan-xxx in the first field..:
The user is allowed to enter b1c1-!*> in the other field.
User cannot enter 1b1c->!* because the first character is expected to be an alphabet not number.
So the first field will define a format definition for a (alphabets), n (numbers), a placeholder, and x (any characters).
What is the easy way to perform this in UI5? I read something related to mask input but I am not sure how to implement it.
As you already guessed, the control sap.m.MaskInput can be leveraged for this kind of use case.
Here is a demo:
globalThis.onUI5Init = () => sap.ui.require([
"sap/ui/core/mvc/XMLView",
"sap/ui/model/json/JSONModel",
"sap/ui/core/Core",
], async (XMLView, JSONModel, core) => {
"use strict";
const control = await XMLView.create({
definition: `<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns:form="sap.ui.layout.form"
xmlns="sap.m"
xmlns:core="sap.ui.core"
core:require="{ StringType: 'sap/ui/model/type/String' }"
height="100%"
>
<App>
<Page showHeader="false">
<form:SimpleForm
editable="true"
layout="ColumnLayout"
>
<Label text="Mask"/>
<Input
value="{
path: '/maskValue',
type: 'StringType',
constraints: {
search: '^$|^[-9ax]+$'
}
}"
placeholder="Example: a9a9-xxx (case sensitive)"
/>
<Label
text="Masked Input"
displayOnly="{= !%{/maskValue}}"
/>
<MaskInput
mask="{/maskValue}"
editable="{= !!%{/maskValue}}"
>
<rules>
<MaskInputRule
maskFormatSymbol="x"
regex="[^_]"
/>
</rules>
</MaskInput>
</form:SimpleForm>
</Page>
</App>
</mvc:View>`,
models: new JSONModel(),
});
core.getMessageManager().registerObject(control, true);
control.placeAt("content");
});
<script id="sap-ui-bootstrap"
src="https://sdk.openui5.org/nightly/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core,sap.m,sap.ui.unified,sap.ui.layout"
data-sap-ui-async="true"
data-sap-ui-oninit="onUI5Init"
data-sap-ui-theme="sap_horizon_dark"
data-sap-ui-compatversion="edge"
data-sap-ui-excludejquerycompat="true"
data-sap-ui-xx-waitfortheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>
MaskInput has an aggregation named <rules> which awaits n-MaskInputRules.
sap.m.MaskInput contains already two default rules:
"9" for /[0-9]/
"a" for /[a-zA-Z]/
Additional rule added: "x" for any characters excluding the default placeholder symbol (_). The corresponding regex is /[^_]/.
For further references, take a look at "Writing a regular expression pattern".
Optionally, you could apply the mask in the second Input only when the first Input has passed its value to the model successfully. For this, you could validate the entry via String type with the search constraint regex ^$|^[-9ax]+$ which allows..:
^$: empty string
|: or
^[-9ax]+$: from the beginning (^) till the end (+$), only -, 9, a, or x.
And finally, let the framework handle UI Messages and ValueState in order to make any invalid inputs visible to the user.

This regex does not work in Chrome

Hi i just put up a validation function in jScript to validate filename in fileupload control[input type file]. The function seems to work fine in FF and sometimes in ie but never in Chrome. Basically the function tests if File name is atleast 1 char upto 25 characters long.Contains only valid characters,numbers [no spaces] and are of file types in the list. Could you throw some light on this
function validate(Uploadelem) {
var objRgx = new RegExp(/^[\w]{1,25}\.*\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/);
objRgx.ignoreCase = true;
if (objRgx.test(Uploadelem.value)) {
document.getElementById('moreUploadsLink').style.display = 'block';
} else {
document.getElementById('moreUploadsLink').style.display = 'none';
}
}
EDIT:
Nope still does not seem to work , i am using IE 8(tried all the compatibility modes), Chrome v8.0, FF v 3.6.
Here is a html snippet in which i wired up the validate function,
<div>
<input type="file" name="attachment" id="attachment" onchange="validate(this)" />
<span class="none">Filename should be within (1-25) letters long. Can Contain only letters
& numbers</span>
<div id="moreUploads">
</div>
<div id="moreUploadsLink" style="display: none;">
Attach another File</div>
</div>
It works perfectly for me. How do you call the validate function ? – M42
You tried this on Google Chrome and IE 8 ? i added HTML Snippet in where in i used all of the recommended regX. No Clues as to why doesn't work!!
Mike, i am unable to comment your post here So this is for you.
The Validation Fails for which ever file i choose in the html input. I Also wired the validation in onblur event but proves same. The validate function will mimic the asp.net regular expression validator which displays validation error message when regular expression is not met.
Try simplifying your code.
function validate(Uploadelem) {
var objRgx = /^[\w]{1,25}\.+(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/i;
if (objRgx.test(Uploadelem.value)) {
document.getElementById('moreUploadsLink').style.display = 'block';
} else {
document.getElementById('moreUploadsLink').style.display = 'none';
}
}
Your specification is hazy, but it appears that you want to allow dots within filenames (in addition to the dot that separates filename and extension).
In that case, try
var objRbx = /^[\w.]{1,25}\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/i;
This allows filenames that consist only of the characters a-z, A-Z, 0-9, _ and ., followed by a required dot and one of the specified extensions.
As far as I know, Chrome adds a path in front of the filename entered, so you have just to change your regex from:
/^[\w]{1,25}\.*\.(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/
to:
/\b[\w]{1,25}\.+(jpg|gif|png|jpeg|doc|docx|pdf|txt|rtf)$/
SOLVED
Primary reason that all [CORRECT regx pattern] did not work is Different browsers returned different values for HTML File Input control.
Firefox: Returns the File Upload controls FileName {As Expected}
Internet Explorer: Returns the Full Path to the File from Drive to File [Pain in the Ass]
Chrome: Returns a fake path as [C:\FakePath\Filename.extension]
I got a solution to the thing for chrome and FF but not IE.
Chrome and Firefox:
use FileUploadControlID.files[0].fileName or FileUploadControlID.files[0].name
IE
Again biggest pain in the ass [someone suggest a solution]
Valid Regex to Validate both fileName and Extension would be:
/\b([a-zA-Z0-9._/s]{3,50})(?=(\.((jpg)|(gif)|(jpeg)|(png))$))/i
1.File Nameshould be between 3 and 50 characters
2. Only jpg,gif,jpeg,png files are allowed

Replacing a substring using regular expressions

I want to add a call to a onclick event in any href that includes a mailto: tag.
For instance, I want to take any instance of:
<a href="mailto:user#domain.com">
And change it into:
<a href="mailto:user#domain.com" onclick="return function();">
The problem that I'm having is that the value of the mailto string is not consistent.
I need to say something like replace all instances of the '>' character with 'onclick="return function();">' in strings that match '<a href="mailto:*">' .
I am doing this in ColdFusion using the REreplacenocase() function but general RegEx suggestions are welcome.
The following will add your onclick to all mailto links contained withing a string str:
REReplaceNoCase(
str,
"(<a[^>]*href=""mailto:[^""]*""[^>]*)>",
"\1 onclick=""return function();"">",
"all"
)
What this regular expression will do is find any <a ...> tag that looks like it's an email link (ie. has an href attribute using the mailto protocol), and add the onclick attribute to it. Everything up to the end of the tag will be stored into the first backreferrence (referred to by \1 in the replacement string) so that any other attributes in the <a> will be preserved.
If the only purpose of this is to add a JavaScript event handler, I don't think Regex is the best choice. If you use JavaScript to wire up your JavaScript events, you'll get more graceful degradation if JS is not available (e.g. nothing will happen, instead of having onclick cruft scattered throughout your markup).
Plus, using the DOM eliminates the possibility of missing matches or false positives that can occur from a Regex that doesn't perfectly anticipate every possible markup formation:
function myClickHandler() {
//do stuff
return false;
}
var links = document.getElementsByTagName('a');
for(var link in links) {
if(link.href.indexOf('mailto:') == 0) {
link.onclick = myClickHandler;
}
}
Why wouldn't you do this on the frontend with a library like jQuery?
$(function(){
$("a[href^=mailto]").click(function(){
// place the code you want to execute here
})
});