Search This Blog

Showing posts with label Regex. Show all posts
Showing posts with label Regex. Show all posts

Saturday, 7 December 2019

OR condition in regular expression

=>Web API
using System.ComponentModel.DataAnnotations;

[RegularExpression(@"^(Y)|(N)$", ErrorMessage = "IsHandicap can only be Y or N.")]
public string IsHandicap{ getset; }

=>C Sharp
using System.Text.RegularExpressions;


string regex = @"^(Y)|(N)$";
string inputString = "Y";
Match match = Regex.Match(inputString, regex);

=>Java Script
<script>
    function Validate() {
        var text = document.getElementById("TextBox1").value;
        var pattern = "^(Y)|(N)$";
        var result = text.match(pattern);
        if (!result)
            alert("IsHandicap can only be Y or N.");
    }
</script>

<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return Validate();" />


Note:- Input string only valid when IsHandicap field value "Y" and "N".


[] - Find any character matching between in the square brackets.
() - Find matching character or word in the brackets.

Regular expression for mobile number with fix country code

=>Web API
using System.ComponentModel.DataAnnotations;

[RegularExpression(@"^(91)?\d{10}$", ErrorMessage = "invalid country code or mobile no.")]   
public string mobileno { getset; }

=>C Sharp

using System.Text.RegularExpressions;

string regex = @"^(91)?\d{10}$";
string inputString = "919876543210";
Match match = Regex.Match(inputString, regex);

=>Java Script
<script>
    function Validate() {
        var text = document.getElementById("TextBox1").value;
        var pattern = "^(91)?\d{10}$";
        var result = text.match(pattern);
        if (!result)
            alert("invalid country code or mobile no.");
    }
</script>

<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return Validate();" />


Note:- Input string only valid when mobile no passed with Indian country code i.e. 91.