I want add validation with phone and email

Harun Ergün 260 Reputation points
2023-06-08T14:29:06.58+00:00

If the user wants to register with the same email and phone, I want to get a warning that this email and phone have been registered before. I tried a lot of Ajax code about this, but I was not successful. Can you help?

@model WebApplication1.Models.Class1
@{
    Layout = null;
}


<script src="~/Scripts/jquery-3.7.0.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<head>
    <style>
        .bold-text {
            font-weight: bold;
        }
    </style>
</head>


<script>
    $(function () {
        $('#DrpSehir').change(function () {
            var id = $('#DrpSehir').val();
            $.ajax({
                url: '/FormExample1/ilcegetir',
                data: { p: id },
                type: "POST",
                dataType: "Json",
                success: function (data) {
                    console.log(data);
                    $('#Drpilce').empty();
                    for (var i = 0; i < data.length; i++) {
                        $('#Drpilce').append("<option value='" + data[i].Text + "'>" + data[i].Text + "</Option>");
                    }
                }
            });
        });
    });
</script>

<br />
<div class="row">
    <div class="col-6">



        @Html.Label("İller", htmlAttributes: new { @class = "bold-text" })
        @Html.DropDownList("DrpSehir", Model.Sehirler, "---Seçiniz---", new { @class = "form-control", @required = "required" })
        <div class="invalid-feedback">
            Lütfen İl Seçiniz!
        </div>
        <div class="valid-feedback">
            Güzel Görünüyor!
        </div>
    </div>
    <div class="col-6">

        @Html.Label("İlçeler", htmlAttributes: new { @class = "bold-text" })
        @Html.DropDownList("Drpilce", Model.ilceler, "---Seçiniz---", new { @class = "form-control", @required = "required" })


        <div class="valid-feedback">
            Güzel Görünüyor!
        </div>



    </div>
</div>


@{
    ViewBag.Title = "ISKO DÜNYASINA HOŞGELDİNİZ!";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="~/Scripts/jquery-3.7.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<br />
<br />
<head>
    <style>
        div.ex1 {
            margin: 60px;
        }

        .bold-text {
            font-weight: bold;
        }
    </style>

</head>

<body>
    <div class="ex1">
        <form action="/FormExample1/Create" method="post" id="myForm" class="was-validated" onsubmit="return demo()">
            @*Text*@
            <div class="row">
                <div class="col-6">
                    <label for="isimgiris" class="form-label"><b>İsim</b></label>
                    <input type="text" name="UserName" ıd="UserName" class="form-control" placeholder="İsim Giriniz.." required>
                    <div class="invalid-feedback">
                        Lütfen İsminizi Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>


                <br />

                <div class="col-6">
                    <label for="soyisimgiris" class="form-label"><b>Soyisim</b></label>
                    <input type="text" name="UserSurName" ıd="UserName" class="form-control" placeholder="Soyisim Giriniz.." minlength="2" maxlength="30" required>
                    <div class="invalid-feedback">
                        Lütfen Soyisminizi Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>
                @*DROPDOWNLİST-WİTH-SQL*@
            </div>


            @{Html.RenderAction("Deneme");}







            <br />
            @*RADİO BUTTON*@
            <div class="row">
                <div class="col">
                    <label><b>Cinsiyet :</b></label>
                    <br />
                    <br />
                    <div class="form-check">
                        <input type="radio" class="form-check-input" id="Gender" required="" name="Gender" value="0" checked>Erkek
                        <label class="form-check-label" for="radio1"></label>
                    </div>
                    <div class="form-check">
                        <input type="radio" class="form-check-input" id="Gender" required="" name="Gender" value="1">Kadın
                        <label class="form-check-label" for="radio2"></label>
                    </div>
                </div>
                <br />
                <br />
                <div class="col">
                    <label><b>Aslerlik Durumu :</b></label>
                    <br />
                    <br />
                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                        <input type="radio" class="form-check-input" id="Military" required="" name="Military" value="0" checked>Yapıldı
                        <label class="form-check-label" for="radio1"></label>
                    </div>
                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                        <input type="radio" class="form-check-input" id="Military" required="" name="Military" value="1">Tecilli
                        <label class="form-check-label" for="radio2"></label>
                    </div>
                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                        <input type="radio" class="form-check-input" id="Military" required="" name="Military" value="2">Muaf
                        <label class="form-check-label" for="radio2"></label>
                    </div>
                </div>
                <br />
                <br />
                <div class="col">
                    <label><b>Evlilik Durumu :</b></label>
                    <br />
                    <br />
                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                        <input type="radio" class="form-check-input" id="Marital" required="" name="Marital" value="0" checked>Evli
                        <label class="form-check-label" for="radio1"></label>
                    </div>
                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                        <input type="radio" class="form-check-input" id="Marital" required="" name="Marital" value="1">Bekar
                        <label class="form-check-label" for="radio2"></label>
                    </div>
                </div>
            </div>
            <br />
            <br />
            @*Text*@
            <div class="row">
                <div class="col-6">
                    <label for="telefon1" class="form-label"><b>Telefon</b></label>
                    <input type="tel" name="Phone" id="Phone" pattern="[0-9]{11}" required class="form-control" placeholder="0(XXX) XXX-XX-XX">
                    <div class="invalid-feedback">
                        Lütfen Telefon Numaranızı 11 Hane Olacak Şekilde Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>
                <br />
                <div class="col-6">
                    <label for="telefon2" class="form-label"><b>Telefon 2</b></label>
                    <input type="tel" name="Phone2" id="Phone2" pattern="[0-9]{11}" required class="form-control" placeholder="0(XXX) XXX-XX-XX">
                    <div class="invalid-feedback">
                        Lütfen Telefon Numaranızı 11 Hane Olacak Şekilde Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>
            </div>
            <br />
            <div class="row">
                <div class="col-6">
                    <label for="emailgiris" class="form-label"><b>Email</b></label>
                    <input type="email" name="Email" id="Email" required="" class="form-control" placeholder="info@info.com şeklinde mail adresinizi giriniz..">
                    <div class="invalid-feedback">
                        Lütfen Email Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>
                <div class="col-6">
                    <label for="emailgiris" class="form-label"><b>Email Tekrar</b></label>
                    <input type="email" name="Email2" id="Email2" required="" class="form-control" placeholder="Aynı Mail Adresini Tekrar Giriniz.">
                    <div class="invalid-feedback">
                        Lütfen Email Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>
            </div>
            <br />

            @*TARİH*@
            <div class="row">

                <div class="col-6">
                    @Html.Label("Tarih", "Lisans Başlangıç Tarihi", htmlAttributes: new { @class = "control-label col-mb-3 bold-text" })
                    <input type="date" class="form-control" id="lisansBaslangicTarih" required="" name="lisansBaslangicTarih" placeholder="Lisans Başlangıç Tarihi Giriniz..">
                    <div class="invalid-feedback">
                        Lütfen Lisans Başlangıç Tarihini Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>


                <div class="col-6">
                    @Html.Label("Tarih", "Lisans Bitiş Tarihi", htmlAttributes: new { @class = "control-label col-mb-3 bold-text" })
                    <input type="date" class="form-control" id="lisansBitisTarih" required="" name="lisansBitisTarih" placeholder="Lisans Bitiş Tarihi Giriniz..">
                    <div class="invalid-feedback">
                        Lütfen Lisans Bitiş Tarihi Giriniz!
                    </div>
                    <div class="valid-feedback">
                        Güzel Görünüyor!
                    </div>
                </div>
            </div>

            <br />

            @*DROPDOWNLİST*@
            <div class="row">
                <div class="col-6">
                    <label class="form-check-label" for="exampleCheck1"><b>Yabancı Dil</b></label>
                    <div class="dropdown">

                        <select id="YabanciDil" name="YabanciDil" class="form-control" required="" placeholder="Yabancı Dil Seçiniz..">
                            <option value="" disabled selected hidden>Yabancı Dil Seçiniz..</option>
                            <option>İngilizce</option>
                            <option>Fransızca</option>
                            <option>Almanca</option>

                        </select>
                        <div class="invalid-feedback">
                            Lütfen Yabancı Dil Seçiniz !
                        </div>
                        <div class="valid-feedback">
                            Güzel Görünüyor!
                        </div>
                    </div>
                </div>

                <div class="col-6">
                    <label class="form-check-label" for="exampleCheck1"><b>Seviye</b></label>
                    <div class="dropdown">

                        <select id="YabanciDil2" name="YabanciDil2" class="form-control" required="" placeholder="Yabancı Dil Seviyesi Seçiniz..">
                            <option value="" disabled selected hidden>Seviye Seçiniz..</option>
                            <option>Az</option>
                            <option>Orta</option>
                            <option>İyi</option>
                        </select>
                        <div class="invalid-feedback">
                            Lütfen Yabancı Dil Seçiniz !
                        </div>
                        <div class="valid-feedback">
                            Güzel Görünüyor!
                        </div>
                    </div>
                </div>
            </div>
            <br />

            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" required="" id="flexSwitchCheckDefault">
                <label class="form-check-label" for="flexSwitchCheckDefault"> <a href="~/FormExample1/About" target="_blank">KVKK Metnini </a> Kabul Ediyorum.</label>
                <div class="invalid-feedback">
                    Lütfen KVKK Onayı Veriniz !
                </div>
                <div class="valid-feedback">
                    Güzel Görünüyor!
                </div>
            </div>


            <br />
            <br />
            @*BUTTON*@
            <center>
                <button type="submit" id="btn1" class="btn btn-success">Gönder</button>
            </center>
        </form>
    </div>
</body>




<script>
    $(document).ready(function () {
        $('#Phone, #Phone2').on('keyup', function () {
            var phone = $('#Phone').val();
            var phone2 = $('#Phone2').val();

            if (phone === phone2) {
                swal.fire(
                    'Telefon Numaraları Aynı',
                    'Telefon 2 farklı olsun !',
                    'error'
                )

                return false;
            }
        });
    });
    
</script>

@*KVKK AKTİF OLDUĞUNDA ALINAN ALERT*@
<script>
    var switchInput = document.getElementById('flexSwitchCheckDefault');

    switchInput.addEventListener('change', function () {
        if (switchInput.checked) {
            swal.fire("KVKK'yı kabul ettiniz!");
        } else {
            swal.fire("KVKK'yı kabul etmediniz!");
        }
    });
</script>
@*POST EDİLDİĞİNDE BAŞARILI VE BAŞARISIZ ŞEKLİNDE DÖNÜŞ YAPAN KOD*@
<script>
        function demo() {
            // AJAX kullanarak formu sunucuya gönder
            $.ajax({
                url: "/FormExample1/Create",
                method: "POST",
                data: $("form").serialize(),
                success: function (response) {
                    swal.fire("Tebrikler!", "Kaydın başarı ile alındı!", "success");
                    $("form")[0].reset();
                },
                error: function () {
                    swal.fire("Hata oluştu!", "Sanırım bazı şeyler yanlış gitti!", "error");

                }
            });

            return false; // Formun otomatik gönderimini engelle
        }
    </script>
@*WAS VALİDATED KODU*@
<script>

    // Example starter JavaScript for disabling form submissions if there are invalid fields
    (function () {
        'use strict'

        // Fetch all the forms we want to apply custom Bootstrap validation styles to
        var forms = document.querySelectorAll('.needs-validation')

        // Loop over them and prevent submission
        Array.prototype.slice.call(forms)
            .forEach(function (form) {
                form.addEventListener('submit', function (event) {
                    if (!form.checkValidity()) {
                        event.preventDefault()
                        event.stopPropagation()
                    }

                    form.classList.add('was-validated')
                }, false)
            })
    })()
</script>











using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
using System.Globalization;
using Microsoft.Ajax.Utilities;
using System.Web.WebPages;
using System.Xml.Linq;
using System.Web.UI.WebControls;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.Remoting.Contexts;
using System.Data.SqlClient;
using System.Web.Helpers;
using System.Data.Entity.Validation;

namespace WebApplication1.Controllers
{
    public class FormExample1Controller : Controller
    {

        ISKOMENUEntities3 context = new ISKOMENUEntities3();
        public ISKOMENUEntities3 ISKOMENUEntities { get; private set; }
        public object Email { get; private set; }



        // GET: FormExample1
        ISKOMENUEntities3 db = new ISKOMENUEntities3();

        Class1 cs = new Class1();

        public ActionResult Deneme()
        {


            cs.Sehirler = new SelectList(db.Tbliller, "id", "ad");
            cs.ilceler = new SelectList(db.tblilceler, "ilceid", "ilcead");


            return View(cs);
        }

        public JsonResult ilcegetir(int p)
        {
            var ilceler = (from x in db.tblilceler
                           join y in db.Tbliller on x.Tbliller.id equals y.id
                           where x.Tbliller.id == p
                           select new
                           {
                               Text = x.ilcead,
                               Value = x.ilceid.ToString()
                           }).ToList();
            return Json(ilceler, JsonRequestBehavior.AllowGet);
        }





        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(FormCollection form)
        {



            ISKOMENUEntities3 db = new ISKOMENUEntities3();
            Users1 model = new Users1();
            try
            {


                model.UserName = form["UserName"].Trim();

                model.UserSurName = form["UserSurName"].Trim();

                int id = Convert.ToInt32(form["DrpSehir"].Trim());
                model.City = (from s in db.Tbliller where s.id == id select s.ad).FirstOrDefault();

                model.City2 = form["Drpilce"].Trim();

                model.Gender = Int16.Parse(form["Gender"]);

                model.Military = Int16.Parse(form["Military"]);

                model.Marital = Int16.Parse(form["Marital"]);

                model.Phone = form["Phone"].Trim();

                model.Phone2 = form["Phone2"].Trim();
                model.Email = form["Email"].Trim();


                if (form["lisansBaslangicTarih"] != "")
                    model.LisansBaslangicTarih = DateTime.Parse(form["lisansBaslangicTarih"]);
                if (form["lisansBitisTarih"] != "")
                    model.LisansBitisTatih = DateTime.Parse(form["lisansBitisTarih"]);

                model.YabanciDil = form["YabanciDil"];

                model.YabanciDil2 = form["YabanciDil2"];

                model.KayitTarihi = DateTime.Today;



                db.Users1.Add(model);

                db.SaveChanges();

                return View();
            }

            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }



        }

            public ActionResult About()
            {
                ViewBag.Message = "KVKK METNİ ;";

                return View();
            }



        }
    }

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 25,551 Reputation points Microsoft Vendor
    2023-06-09T10:16:48.56+00:00

    Hi @Harun Ergün,

    You can refer to the code below.You can add a message box.

     <center>
                    <button type="submit" id="btn1" class="btn btn-success">Gönder</button>
                </center>
                <span id="message"></span>
    
     function demo() {
        var phone = $("#Phone").val();
        var email = $("#Email").val();
        $.ajax({
            type: "POST",
            url: "/FormExample1/EmailExists",
            data: '{ phone: "' + phone + '",email: "' + email + '"}',
    
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert(response);
                var message = $("#message");
                if (response) {
                    message.css("color", "green");
                    message.html("success");
                    $.ajax({
                        url: "/FormExample1/Create",
                        method: "POST",
                        data: $("form").serialize(),
                        success: function (response) {
                            swal.fire("Tebrikler!", "Kaydın başarı ile alındı!", "success");
                            $("form")[0].reset();
                        },
                        error: function () {
                            swal.fire("Hata oluştu!", "Sanırım bazı şeyler yanlış gitti!", "error");
    
                        }
                    });
    
                    return false; // Formun otomatik gönderimini engelle
    
                }
                else {
    
                    message.css("color", "red");
                    message.html("Email OR Phone already exists");
                }
            }
        });
    }
    

    You need to fetch data from database. Uncommented below are my tests. Because don't know which table the data is in, you can refer to the notes and modify it according to your own table.

    public JsonResult EmailExists(string phone,string email)
            {
                // ISKOMENUEntities3 db = new ISKOMENUEntities3();
                // bool isValid = !db.Users.ToList().Exists(p => p.Email.Equals(email, StringComparison.CurrentCultureIgnoreCase));
                //&& !db.Users.ToList().Exists(p => p.Phone.Equals(phone, StringComparison.CurrentCultureIgnoreCase)
                bool isValid = !String.Equals(phone, "12345678978", StringComparison.OrdinalIgnoreCase)  
                    && !String.Equals(email, "123@123.com", StringComparison.OrdinalIgnoreCase);
                
                return Json(isValid);
               
            }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,686 Reputation points
    2023-06-08T15:15:36.6266667+00:00

    you could use the unobtrusive validation and remote validators.

    https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0

    if you want to code your own, you need to remember that the ajax calls are async, so after the calls are complete you will need to resubmit the form. $.ajax() returns a promise the validation can use to check the results.

    0 comments No comments